#include "surface.hpp"
#include <SDL_image.h>

namespace yep
{
Surface::Surface(SDL_Surface* surface, bool own):
    Canvas(surface, own)
{
}

Surface::Surface(SDL_RWops* loadFrom, bool freesrc):
    Canvas(IMG_Load_RW(loadFrom, freesrc), true)
{
}

Surface::Surface(const string& file):
    Canvas(IMG_Load(file.c_str()), true)
{
}

Surface::Surface(Uint16 width, Uint16 height, Uint8 bpp, Uint32 flags):
    Canvas(NULL, true)
{
    Uint32 rmask, gmask, bmask, amask;
    switch(bpp)
    {
    case 8:
    case 24:
    case 32:
        rmask = 0xFF000000;
        gmask = 0x00FF0000;
        bmask = 0x0000FF00;
        amask = 0x000000FF;
        break;
    case 15:
        rmask = 0x7C00;
        gmask = 0x03E0;
        bmask = 0x001F;
        amask = 0x0000;
        break;
    case 16:
        rmask = 0xF800;
        gmask = 0x07E0;
        bmask = 0x001F;
        amask = 0x0000;
        break;
    }
    surface = SDL_CreateRGBSurface(flags, width, height, bpp, rmask, gmask, bmask, amask);
}

Surface::Surface(const Surface &surface):
    Canvas(surface.surface, surface.owner)
{
    if(owner)
        this->surface->refcount++;
}


Surface::~Surface()
{
}

void Surface::draw(Canvas& canvas, const Vector2& position)
{
    SDL_BlitSurface(surface, NULL, canvas.getSurface(), position);
}

void Surface::draw( Canvas &canvas, const Vector2 &position, const Vector2 &sectionPosition, const Vector2 &sectionSize )
{
    SDL_Rect section{(Sint16)sectionPosition.x, (Sint16)sectionPosition.y, (Uint16)sectionSize.x, (Uint16)sectionSize.y};
    SDL_BlitSurface(surface, &section, canvas.getSurface(), position);
}

}
